package com.guoxue.action.front;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.guoxue.domain.TapesRecordsVo;
import com.guoxue.domain.UserVo;
import com.guoxue.service.ITapesRecordsService;
import com.guoxue.util.LoggerUtil;
import com.guoxue.util.OtherUtils;
import com.guoxue.util.codeSwitch.zt;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URLDecoder;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class OSSCallBackAction {

	@Resource
	private ITapesRecordsService tapesRecordsService;

	@ResponseBody
	@RequestMapping({ "/getCallBack" })
	public void getCallBack(HttpServletRequest request, HttpServletResponse response) throws IOException {
		zt.ts.function(); // 已作废?
		
		String callbackFunName = "";
		try {
			String ossCallbackBody = GetPostBody(request.getInputStream(), Integer.parseInt(
					(request.getHeader("content-length") == null) ? "0" : request.getHeader("content-length")));
			boolean ret = VerifyOSSCallbackRequest(request, ossCallbackBody);
			callbackFunName = request.getParameter("callback");
			System.out.println("verify result:" + ret);
			System.out.println("OSS Callback Body:" + ossCallbackBody);

			if (ret) {
				if ((callbackFunName == null) || (callbackFunName.equalsIgnoreCase(""))) {
					TapesRecordsVo tr = new TapesRecordsVo();
					// UserVo user = (UserVo)
					// request.getSession().getAttribute("user");
					// System.out.println(user);
					String[] body = ossCallbackBody.split("&");
					if ((body != null) && (body.length != 0)) {
						for (String strings : body) {
							if ((strings != null) && (strings.trim().length() != 0)) {
								String[] x = strings.split("=");
								if (x[0].equals("object"))
									tr.setTapes(x[1]);
								else if (x[0].equals("size"))
									tr.setSize(Integer.valueOf(x[1]));
								else if (x[0].equals("flag")) {
									tr.setFlag(x[1]);
								}
							}
						}
					}
					tr.setCommitTime(OtherUtils.getCurrentDate());
					this.tapesRecordsService.saveTapesRecords(tr);
					System.out.println(tr.getTapes() + tr.getFlag() + tr.getSize());
					response(request, response, "{\"Status\":\"OK\"}", 200);
					return;
				}
				response(request, response, "{\"Status\":\"verdify not ok\"}", 400);

				return;
			}
			response(request, response, "{\"Status\":\"verdify not ok\"}", 400);
		} catch (Exception e) {
			response(request, response, "{\"Status\":\"verdify not ok\"}", 400);
			e.printStackTrace();
		}
	}

	private boolean doCheck(String content, byte[] sign, String publicKey) {
		try {
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			byte[] encodedKey = BinaryUtil.fromBase64String(publicKey);
			PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
			Signature signature = Signature.getInstance("MD5withRSA");
			signature.initVerify(pubKey);
			signature.update(content.getBytes());
			boolean bverify = signature.verify(sign);
			return bverify;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return false;
	}

	private String GetPostBody(InputStream is, int contentLen) {
		if (contentLen > 0) {
			int readLen = 0;
			int readLengthThisTime = 0;
			byte[] message = new byte[contentLen];
			try {
				while (readLen != contentLen) {
					readLengthThisTime = is.read(message, readLen, contentLen - readLen);
					if (readLengthThisTime == -1) {
						break;
					}
					readLen += readLengthThisTime;
				}
				return new String(message);
			} catch (IOException e) {
				LoggerUtil.error(e);
			} finally {
				try {
					is.close();
				} catch (IOException e) {
					LoggerUtil.error(e);
				}
			}
		}
		return "";
	}

	private boolean VerifyOSSCallbackRequest(HttpServletRequest request, String ossCallbackBody)
			throws NumberFormatException, IOException {
		boolean ret = false;
		String autorizationInput = new String(request.getHeader("Authorization"));
		String pubKeyInput = request.getHeader("x-oss-pub-key-url");
		byte[] authorization = BinaryUtil.fromBase64String(autorizationInput);
		byte[] pubKey = BinaryUtil.fromBase64String(pubKeyInput);
		String pubKeyAddr = new String(pubKey);
		if ((!(pubKeyAddr.startsWith("http://gosspublic.alicdn.com/")))
				&& (!(pubKeyAddr.startsWith("https://gosspublic.alicdn.com/")))) {
			System.out.println("pub key addr must be oss addrss");
			return false;
		}
		String retString = executeGet(pubKeyAddr);
		retString = retString.replace("-----BEGIN PUBLIC KEY-----", "");
		retString = retString.replace("-----END PUBLIC KEY-----", "");
		String queryString = request.getQueryString();
		String uri = request.getRequestURI();
		String decodeUri = URLDecoder.decode(uri, "UTF-8");
		String authStr = decodeUri;
		if ((queryString != null) && (!(queryString.equals("")))) {
			authStr = authStr + "?" + queryString;
		}
		authStr = authStr + "\n" + ossCallbackBody;
		ret = doCheck(authStr, authorization, retString);
		return ret;
	}

	private String executeGet(String url) {
		BufferedReader in = null;
		String content = null;
		try {
			DefaultHttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet();
			request.setURI(new URI(url));
			HttpResponse response = client.execute(request);

			in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			content = sb.toString();
		} catch (Exception e) {
			LoggerUtil.error(e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (Exception e) {
					LoggerUtil.error(e);
				}
			}
		}
		return content;
	}

	private void response(HttpServletRequest request, HttpServletResponse response, String results, int status)
			throws IOException {
		String callbackFunName = request.getParameter("callback");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		response.addHeader("Content-Length", String.valueOf(results.length()));
		if ((callbackFunName == null) || (callbackFunName.equalsIgnoreCase("")))
			response.getWriter().println(results);
		else {
			response.getWriter().println(callbackFunName + "( " + results + " )");
		}
		response.setStatus(status);
		JSONObject json = new JSONObject();
		if (status == 200) {
			json.put("code", Integer.valueOf(200));
			json.put("message", "上传成功");
		} else {
			json.put("code", Integer.valueOf(400));
			json.put("message", "上传失败");
		}
		response.getWriter().println(json);
		System.out.println(json);
		response.flushBuffer();
	}
}